package com.example.smartwaterapi.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.smartwaterapi.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Insert;

import java.time.LocalDateTime;

/**
 * 用户Mapper接口
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {
    
    /**
     * 通过openid查询用户ID
     * @param openid 微信openid
     * @return 用户ID
     */
    @Select("SELECT id FROM users WHERE openid = #{openid}")
    Long selectIdByOpenid(String openid);
    
    /**
     * 检查openid是否存在并获取用户ID（更可靠的方式）
     * @param openid 微信openid
     * @return 用户ID，如果不存在则返回null
     */
    @Select("SELECT id FROM users WHERE openid = #{openid} LIMIT 1")
    Long getIdByOpenid(String openid);
    
    /**
     * 通过公众号openid查询用户
     * @param wxOpenid 微信公众号openid
     * @return 用户对象
     */
    @Select("SELECT * FROM users WHERE wx_openid = #{wxOpenid} LIMIT 1")
    User selectByWxOpenid(String wxOpenid);
    
    /**
     * 通过公众号openid获取用户ID
     * @param wxOpenid 微信公众号openid
     * @return 用户ID
     */
    @Select("SELECT id FROM users WHERE wx_openid = #{wxOpenid} LIMIT 1")
    Long getIdByWxOpenid(String wxOpenid);
    
    /**
     * 更新用户的公众号openid
     * @param userId 用户ID
     * @param wxOpenid 公众号openid
     * @return 受影响行数
     */
    @Update("UPDATE users SET wx_openid = #{wxOpenid}, updated_at = NOW() WHERE id = #{userId}")
    int updateWxOpenid(Long userId, String wxOpenid);
    
    /**
     * 插入新用户并返回生成的ID
     * @param user 用户对象
     * @return 受影响行数
     */
    @Insert("INSERT INTO users (uuid, phone, nickname, avatar, unlock_password, password_salt, " +
            "openid, wx_openid, unionid, session_key, gender, age, height, weight, " +
            "daily_goal, reminder_enabled, reminder_interval, membership_level, " +
            "points, total_points, status, last_login_time, created_at, updated_at) " +
            "VALUES (#{uuid}, #{phone}, #{nickname}, #{avatar}, #{unlockPassword}, #{passwordSalt}, " +
            "#{openid}, #{wxOpenid}, #{unionid}, #{sessionKey}, #{gender}, #{age}, #{height}, #{weight}, " +
            "#{dailyGoal}, #{reminderEnabled}, #{reminderInterval}, #{membershipLevel}, " +
            "#{points}, #{totalPoints}, #{status}, #{lastLoginTime}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insertUserAndReturnId(User user);
    
    /**
     * 通过openid直接更新用户信息
     * @param nickname 昵称
     * @param sessionKey 会话密钥
     * @param gender 性别
     * @param avatar 头像
     * @param updatedAt 更新时间
     * @param openid 微信openid
     * @return 受影响行数
     */
    @Update("UPDATE users SET nickname = #{nickname}, session_key = #{sessionKey}, gender = #{gender}, " +
           "avatar = #{avatar}, updated_at = #{updatedAt}, last_login_time = #{updatedAt} WHERE openid = #{openid}")
    int updateUserByOpenid(String nickname, String sessionKey, Integer gender, String avatar, 
                          LocalDateTime updatedAt, String openid);
} 